package com.luhaoran.hrm.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class TokenUtils {
    static  String issuer = "admin";
    static  String secretKey = "123456";
    /**
     * 生成Token
     * @param sign 身份标识
     * @param issuedTime 当前时间
     * @param expiresTime 过期时间
     * @return
     * */
    public static String generate(Object sign,Date issuedTime,Date expiresTime){
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String token = JWT.create().withIssuer(issuer)
                .withIssuedAt(issuedTime)
                .withExpiresAt(expiresTime)
                .withClaim("sign",sign.toString())
                .sign(algorithm);
        return token;

    }
    /**
     * 验证token
     * @param token
     * @return token携带的身份标识
     * */
    public static String verify(String token){
        try {
            //创建一个验证器对象
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(issuer).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            return decodedJWT.getClaim("sign").asString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
